package com.dletc.dao.Impl;

import com.dletc.dao.DishDao;
import com.dletc.domain.Dish;
import com.dletc.utils.DBUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class DishDaoImpl implements DishDao {

    @Override
    public void AddDish(Dish dish) {

        try {
            QueryRunner qr = new QueryRunner(DBUtils.getDataSource());

            String sql = "insert into Dish Values(null,?,?)";

            int count = qr.update(sql, dish.getDishName(), dish.getDishMoney());

            System.out.println(count > 0?"菜品添加成功":"菜品添加失败");

        } catch (SQLException throwables) {

            throwables.printStackTrace();
        }
    }

    @Override
    public void deleteById(int DishID) {
        try {
            QueryRunner qr = new QueryRunner(DBUtils.getDataSource());

            String sql = "delete from Dish where DishID = ?";

            int count = qr.update(sql, DishID);

            System.out.println(count > 0?"菜品删除成功":"菜品删除失败");
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    @Override
    public List<Dish> GetAll() {
        List<Dish> list = null;
        try {
            QueryRunner qr = new QueryRunner(DBUtils.getDataSource());
            String sql = "select * from Dish";
            list = qr.query(sql, new BeanListHandler<Dish>(Dish.class));
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return list;
    }

    @Override
    public Dish GetByID(int DishID) {

        Dish dish = null;
        try {
            QueryRunner qr = new QueryRunner(DBUtils.getDataSource());

            String sql = "select * from Dish where DishID = ?";

            dish = qr.query(sql, new BeanHandler<Dish>(Dish.class), DishID);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return dish;
    }

    @Override
    public void UpdateMoney(int DishID, int money) {
        int count = 0;
        try {
            QueryRunner qr = new QueryRunner(DBUtils.getDataSource());

            String sql = "update Dish set DishMoney = ? where DishID = ?";

            count = qr.update(sql, money, DishID);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        System.out.println(count > 0?"商品价格修改成功":"商品价格修改失败");
    }
}
